package org.example.zookeeper.controller;

import org.example.zookeeper.model.Article;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.sql.Date;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

@RestController
public class ArticleController {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @GetMapping("findAllArticles")
    public List<Article> findAllArticles() {
        List<Article> articleList = jdbcTemplate.query("select * from t_article", new RowMapper<Article>() {
            @Override
            public Article mapRow(ResultSet resultSet, int i) throws SQLException {
                Integer id = resultSet.getInt("id");
                String title = resultSet.getString("title");
                String content = resultSet.getString("content");
                Date created = resultSet.getDate("created");
                Date modified = resultSet.getDate("modified");
                String categories = resultSet.getString("categories");
                String tags = resultSet.getString("tags");
                Integer allowComment = resultSet.getInt("allow_comment");
                String thumbnail = resultSet.getString("thumbnail");

                Article article = new Article();
                article.setId(id);
                article.setTitle(title);
                article.setContent(content);
                article.setCreated(created);
                article.setModified(modified);
                article.setCategories(categories);
                article.setTags(tags);
                article.setAllowComment(allowComment);
                article.setThumbnail(thumbnail);

                return article;
            }
        });

        return articleList;
    }
}
